package model

import (
	"context"

	"github.com/zeromicro/go-zero/core/stores/mon"
	"go.mongodb.org/mongo-driver/bson"
)

var _ AuthModel = (*customAuthModel)(nil)

type (
	// AuthModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAuthModel.
	AuthModel interface {
		authModel
		FindOneByUserID(ctx context.Context, uid string) (*Auth, error)
		FindOneByInstallID(ctx context.Context, iid string) (*Auth, error)
	}

	customAuthModel struct {
		*defaultAuthModel
	}
)

// NewAuthModel returns a model for the mongo.
func NewAuthModel(url, db, collection string) AuthModel {
	conn := mon.MustNewModel(url, db, collection)
	return &customAuthModel{
		defaultAuthModel: newDefaultAuthModel(conn),
	}
}

func (m *customAuthModel) FindOneByUserID(ctx context.Context, uid string) (*Auth, error) {

	var data Auth

	err := m.conn.FindOne(ctx, &data, bson.M{"uid": uid})
	switch err {
	case nil:
		return &data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *customAuthModel) FindOneByInstallID(ctx context.Context, iid string) (*Auth, error) {

	var data Auth

	err := m.conn.FindOne(ctx, &data, bson.M{"install_id": iid})
	switch err {
	case nil:
		return &data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
